package com.riki.riki_push;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.huawei.agconnect.config.AGConnectServicesConfig;
import com.huawei.hms.aaid.HmsInstanceId;
import com.huawei.hms.common.ApiException;
import com.huawei.hms.push.HmsMessaging;
import com.riki.riki_push.util.CommonUtil;
import com.riki.riki_push.util.RomUtil;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

import com.xiaomi.mipush.sdk.MiPushClient;

import java.lang.reflect.Method;


/**
 * RikiPushPlugin
 */
public class RikiPushXmPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private MethodChannel channel;
    private Context context;
    private Activity activity;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        context = flutterPluginBinding.getApplicationContext();
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "riki_push_xm");
        channel.setMethodCallHandler(this);
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        try {
            if (call.method.equals("init")) {
                init(call, result);
            } else if (call.method.equals("getXmRegId")) {
                getXmRegId(call, result);
            } else if (call.method.equals("unInit")) {
                unInit(call, result);
            } else {
                result.notImplemented();
            }
        } catch (Exception e) {
            result.notImplemented();
        }

//        try {
//            Method method = this.getClass().getDeclaredMethod(call.method, MethodCall.class, Result.class);
//            method.invoke(this, call, result);
//        } catch (Exception e) {
//            result.notImplemented();
//        }

    }


    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    /**
     * 初始化
     */
    private void init(@NonNull MethodCall call, @NonNull Result result) {
        // 获得参数
        try {
            String appId = CommonUtil.getParam(call, result, "appId");
            String appKey = CommonUtil.getParam(call, result, "appKey");
            if (TextUtils.isEmpty(appId) || TextUtils.isEmpty(appKey)) {
                result.success(0);
            } else {
                MiPushClient.registerPush(this.context, appId, appKey);
                result.success(1);
            }
        } catch (Exception e) {
            result.success(0);
        }
    }


    /**
     * 反初始化
     */
    private void unInit(@NonNull MethodCall call, @NonNull Result result) {
        try {
            MiPushClient.unregisterPush(this.context);
            result.success(1);
        } catch (Exception e) {
            result.success(0);
        }
    }


    /**
     * 获取客户端的 RegId
     */
    private void getXmRegId(@NonNull MethodCall call, @NonNull Result result) {
        try {
            result.success(MiPushClient.getRegId(context));
        } catch (Exception e) {
            result.success(0);
        }
    }


    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding activityPluginBinding) {
        this.activity = activityPluginBinding.getActivity();

        // 动态申请电话和存储权限
        // 引用小米官方SDK: `在非MIUI平台下，如果targetSdkVersion>=23，需要动态申请电话和存储权限，请在申请权限后再调用注册接口，否则会注册失败。`
        /*if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(this.context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this.activity, new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE
                }, 1);
            }
        }*/
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {

    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {

    }

    @Override
    public void onDetachedFromActivity() {

    }
}
